package org.ruoyi.graph2.utils;
// WordDocumentParser.java

import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.ruoyi.graph2.domain.bo.KnowledgeNodeBo;

import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

public class WordDocumentParser {

	public static List<KnowledgeNodeBo> parseDocument(String filePath, String graphGroup) {
		List<KnowledgeNodeBo> nodes = new ArrayList<>();

		try (FileInputStream fis = new FileInputStream(filePath);
			 XWPFDocument document = new XWPFDocument(fis)) {

			String currentTitle = null;
			StringBuilder currentContent = new StringBuilder();
			Map<String, String> numberingMap = new HashMap<>();

			for (XWPFParagraph paragraph : document.getParagraphs()) {
				String text = paragraph.getText().trim();
				if (text.isEmpty()) continue;

				// 检查是否为标题（包含数字序号）
				if (isKnowledgeTitle(text)) {
					// 保存前一个节点
					if (currentTitle != null) {
						KnowledgeNodeBo node = createKnowledgeNode(currentTitle,
							currentContent.toString(), graphGroup, numberingMap);
						if (node != null) {
							nodes.add(node);
						}
					}

					// 开始新的节点
					currentTitle = text;
					currentContent = new StringBuilder();
				} else {
					// 添加到内容
					if (currentTitle != null) {
						if (currentContent.length() > 0) {
							currentContent.append("\n");
						}
						currentContent.append(text);
					}
				}
			}

			// 处理最后一个节点
			if (currentTitle != null) {
				KnowledgeNodeBo node = createKnowledgeNode(currentTitle,
					currentContent.toString(), graphGroup, numberingMap);
				if (node != null) {
					nodes.add(node);
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
		}

		return nodes;
	}

	private static boolean isKnowledgeTitle(String text) {
		// 匹配 "数字." 格式的标题
		Pattern pattern = Pattern.compile("^\\d+(\\.\\d+)*\\..*");
		return pattern.matcher(text).matches();
	}

	private static KnowledgeNodeBo createKnowledgeNode(String title, String content, String graphGroup,
												Map<String, String> numberingMap) {
		// 提取序号和标题文本
		int lastDotIndex = title.lastIndexOf(".");
		String numberPart = title.substring(0, lastDotIndex) + ".";      // "1.1"
		String titleText = title.substring(lastDotIndex + 1);

//		String[] parts = title.split("\\.", 2);
//		if (parts.length < 2) return null;
//
//		String numberPart = parts[0] + ".";
//		String titleText = parts[1].trim();

		// 计算层级深度
		int depth = numberPart.split("\\.").length;

		// 确定节点类型
		String level = (depth >= 4) ? "knowledge_point" : "knowledge_unit";

		return new KnowledgeNodeBo(titleText, content, level, depth, numberPart, graphGroup);
	}
}
